import store from '@/store';
import LocalStorageUtil from "@/utils/local-storage-util";
import DictModel from "@/store/dict/dict.model";
import {StoreDictEnum, TabsActionsEnum, UserMutationEnum} from "@/store/enum/store.enum";

/**
 * @description 工具类
 */
export default class Utils {
    /**
     * @description 获取随机id
     * @param length
     * @returns {string}
     */
    public static uuid(length = 32) {
        const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        let str = ''
        for (let i = 0; i < length; i++) {
            str += num.charAt(Math.floor(Math.random() * num.length))
        }
        return str
    }


    /**
     * @description addEventListener
     * @type {function(...[*]=)}
     */
    public static on = () => {
        return function (element, event, handler, useCapture = false) {
            if (element && event && handler) {
                element.addEventListener(event, handler, useCapture)
            }
        }
    }

    /**
     * @description removeEventListener
     * @type {function(...[*]=)}
     */
    public static off = () => {
        return function (element, event, handler, useCapture = false) {
            if (element && event) {
                element.removeEventListener(event, handler, useCapture)
            }
        }
    }

    /**
     * 查找数据字典，传入code
     */
    public static returnDict(code:string) {
        let arr = [];
        const dictData=store.getters[StoreDictEnum.dict]
        store.getters.dict && store.getters.dict.map(item => {
            if (item.parentCode == code) {//先查找该code下的子集
                arr.push(item);
            }
        });
        //如果子集为空，则只有一条且为最后一级
        if (arr.length == 0) {
            store.getters.dict && store.getters.dict.map(item => {
                if (item.code == code) {
                    arr = item;
                }
            });
        } else if (arr.length > 0) {//如果数组长度>0，处理成树结构
            this.forTree(arr);
        } else {//否则都找不到
            arr = null;
        }
        return arr;
    }
    private static forTree(array:DictModel[]) {
        array.map(item => {
            item.children = [];
            store.getters.dict && store.getters.dict.map(sub => {
                if (sub.parentCode == item.code) {//
                    item.children.push(sub);
                }
            });
            this.forTree(item.children);
        })
    }

	/**
	 * 退出登录清除信息（注意某些用户配置不要删除，具体请在各自store模块中处理）
	 */
	public static clearLoginInfo() {
		store.dispatch(UserMutationEnum.clearUserInfo);
		store.dispatch(StoreDictEnum.clearDict);
		store.dispatch(TabsActionsEnum.delAllVisitedRoutes);
	}
}
